package com.x.component.utils;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.lang.reflect.Method;

import android.os.SystemProperties;
import android.text.TextUtils;
import android.util.Log;

public class BridgeSystemProperties {

	private static final String TAG = "MirrorSystemProperties";

	public static String getSystemProperty(String property, String defaultValue) {
		try {
			return SystemProperties.get(property, defaultValue);
		} catch (Exception e) {
			Log.d(TAG, "Unable to read system properties");
		}
		return defaultValue;
	}

	public static String getSystemPropertyByReflect(String property, String defaultValue) {
		try {
			Class clazz = Class.forName("android.os.SystemProperties");
			Method getter = clazz.getDeclaredMethod("get", String.class);
			String value = (String) getter.invoke(null, property);
			if (!TextUtils.isEmpty(value)) {
				return value;
			}
		} catch (Exception e) {
			Log.d(TAG, "Unable to read system properties");
		}
		return defaultValue;
	}

	public static boolean setSystemProperty(String property, String defaultValue) {
		try {
			SystemProperties.set(property, defaultValue);
			return true;
		} catch (Exception e) {
			Log.d(TAG, "Unable to set system properties");
		}
		return false;
	}

	public static String readSystemVersionInfo() {
		String version = readPersistLicense("system/etc/version");
		return version;
	}

	public static String readSystemSerialNumber() {
		String serialno = SystemProperties.get("ro.serialno", "");
		String serial_number = readPersistLicense("/sys/devices/soc0/serial_number");
		return serialno + serial_number;
	}

	public static String readPersistLicense(String path) {
//		File mParent = new File(Environment.getExternalStorageDirectory().getPath() + "/.twhide")
//		File mParent = new File("/system/etc/.xlinkhide");
//		if (!mParent.exists()) {
//			return "";
//		}
//		File licenseFile = new File(mParent, "xlink.license");
		File licenseFile = new File(path);
		if (licenseFile.exists()) {
			FileReader fr = null;
			BufferedReader br = null;
			try {
				fr = new FileReader(licenseFile);
				br = new BufferedReader(fr);
				String license = br.readLine();
				Log.d("license", "persist license: " + license);
				return license;
			} catch (Exception e) {
				e.printStackTrace();
			} finally {
				if (br != null) {
					try {
						br.close();
					} catch (IOException e) {
						e.printStackTrace();
					}
					br = null;
				}
				if (fr != null) {
					try {
						fr.close();
					} catch (IOException e) {
						e.printStackTrace();
					}
					fr = null;
				}
			}
		}
		return "";
	}

}
